package cn.lds.j375.chlm.serivce.impl;

import cn.hutool.crypto.SecureUtil;
import cn.lds.j375.chlm.dto.ChlmConstant;
import cn.lds.j375.chlm.dto.ResultDTO;
import cn.lds.j375.chlm.entity.User;
import cn.lds.j375.chlm.exception.ChlmException;
import cn.lds.j375.chlm.mapper.UserMapper;
import cn.lds.j375.chlm.serivce.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Service
public class UserSerrviceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public ResultDTO<List<User>> selectUserAll(User user) {

        List<User> users = userMapper.selectUserAll(user);

        if (CollectionUtils.isEmpty(users)){
            return ResultDTO.buildError();
        }

        return ResultDTO.buildSuccess(users);
    }

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public ResultDTO<User> selectUserById(Integer id) throws ChlmException {

        User user = userMapper.selectUserById(id);

        if (Objects.isNull(user)){
            throw new ChlmException(ChlmConstant.UserMsg.QUERY_ERROR);
        }


        return ResultDTO.buildSuccess(user);
    }

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public ResultDTO<User> loginUser(User user) {


        //接收的密码做加密处理
        user.setPassword(SecureUtil.md5(user.getPassword()));

        User loginUser = userMapper.loginUser(user);

        if (Objects.isNull(loginUser)){
            return ResultDTO.buildError(ChlmConstant.UserMsg.LOGIN_ERROR);
        }


        return ResultDTO.buildSuccess(loginUser);
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public ResultDTO regUser(User user) throws ChlmException {

        //将密码加密
        user.setPassword(SecureUtil.md5(user.getPassword()));


        //这里省事不写业务了
        int i = userMapper.regUser(user);

        if (i <= 0){
            throw new ChlmException("用户注册发生异常");
        }

        return ResultDTO.buildSuccess();
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public ResultDTO modifyUser(User user) {

        userMapper.modifyUser(user);
        return ResultDTO.buildSuccess();
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public ResultDTO removeUserById(Integer id) {

        userMapper.removeUserById(id);

        return ResultDTO.buildSuccess();
    }
}
